from fastapi import FastAPI, Depends, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.orm import Session
from models import TreeData
from database import SessionLocal, engine
from crud import get_tree, get_all_trees
import models
from typing import Dict, List, Any
from config import settings

app = FastAPI(title=settings.PROJECT_NAME)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    allow_headers=["*"],
)

# 创建数据库表
models.Base.metadata.create_all(bind=engine)

# 依赖项
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

def create_response(data: Any = None, message: str = "操作成功", success: bool = True, code: int = 200) -> Dict[str, Any]:
    """创建统一的API响应格式"""
    return {
        "message": message,
        "success": success,
        "code": code,
        "data": data
    }

@app.get("/trees/")
def read_all_trees(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    try:
        trees = get_all_trees(db, skip=skip, limit=limit)
        data = [{
            "sample_id": tree.sample_id,
            "inspection_type": tree.inspection_type,
            "species": tree.species,
            "diameter_2024": tree.diameter_2024,
            "diameter_2025": tree.diameter_2025,
            "azimuth": tree.azimuth,
            "horizontal_distance": tree.horizontal_distance,
            "plot_azimuth": tree.plot_azimuth,
            "plot_horizontal_distance": tree.plot_horizontal_distance,
            "x": tree.x,
            "y": tree.y,
            "note": tree.note
        } for tree in trees]
        return create_response(data=data, message="获取树木数据列表成功")
    except Exception as e:
        return create_response(
            data=None, 
            message=f"获取树木数据列表失败: {str(e)}", 
            success=False, 
            code=500
        )

@app.get("/trees/{sample_id}")
def read_tree(sample_id: int, db: Session = Depends(get_db)):
    try:
        tree = get_tree(db, sample_id=sample_id)
        if tree is None:
            return create_response(
                data=None, 
                message=f"未找到ID为{sample_id}的树木数据", 
                success=False, 
                code=404
            )
        
        data = {
            "sample_id": tree.sample_id,
            "inspection_type": tree.inspection_type,
            "species": tree.species,
            "diameter_2024": tree.diameter_2024,
            "diameter_2025": tree.diameter_2025,
            "azimuth": tree.azimuth,
            "horizontal_distance": tree.horizontal_distance,
            "plot_azimuth": tree.plot_azimuth,
            "plot_horizontal_distance": tree.plot_horizontal_distance,
            "x": tree.x,
            "y": tree.y,
            "note": tree.note
        }
        return create_response(data=data, message="获取树木数据成功")
    except Exception as e:
        return create_response(
            data=None, 
            message=f"获取树木数据失败: {str(e)}", 
            success=False, 
            code=500
        )